<template>
  <div>
    <!--条件筛选-->
    <TopFilter ref="topFilter" :list="topFilterList" :cols="3" :labelWidth="110" :collapse="false" @filterChange="changeHandle" @onCollapse="collapseHandle" @resetChange="resetHandler"></TopFilter>
    <!-- 列筛选-->
    <FilterTable
      ref="table"
      columnsRef="lhmServiceAdviserAchievement"
      :columns="columns"
      :dataSource="dataSource"
      :isExportExcel="true"
      exportFileName="服务顾问业绩统计.xlsx"
      :isMemoryPagination="true"
      :isSelectColumn="isSelectColumn"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChangeHandle"
      :onSyncTableData="tableAllData"
    >
      <template slot="controls" slot-scope="props">
        <el-button size="small" type="primary" @click="openHandle">服务顾问业绩统计汇总</el-button>
        <el-button size="small" type="primary" @click="saveHandle">打印</el-button>
      </template>
    </FilterTable>
    <Drawer title="服务顾问业绩统计汇总" :visible.sync="isShowSummary" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <Summary :formData="formData" @close="isShowSummary = false" />
    </Drawer>
    <BasePrint ref="print" :data="printList" template="serviceAdviserAchievement" />
    <!-- printCMZ() {
      this.$refs.print.EXCUTE_PRINT();
    }, -->
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
import dictCode from '@/utils/dictCode';
import { arrayObjDeWeight } from '@/utils/index'; // 去重
import { searchRoleByCode } from '@/api/common/empSelect/index';
// 获取员工
import { getDealerUser } from '@/api/customerRepair/customerComplaint/customerComplaintReception';
import { getServiceAdciserData, searchServiceAdvisor } from '@/api/repair/queryStatistics/queryAccounts';
// 维修类别
import { getfindAllRepairType } from '@/api/repair/business/customer/history';
// 车型
import { getModel } from '@/api/customerRepair/customerCare/insuranceDueRemind/index';
import Summary from './summary';
export default {
  name: 'LHMServiceAdviserAchievement',
  components: {
    Summary
  },
  mixins: [dictionary],
  data() {
    return {
      topFilterList: this.createTopFilterList(),
      dataSource: [],
      isSelectColumn: false,
      // fetchApi: getServiceAdciserData,
      columns: this.createTableCheckColumns(),
      printList: {},
      serviceAdvisorDict: [],
      isShowSummary: false,
      formData: {}
    };
  },
  mounted() {
    // 分页
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.getFwgcsSelectFun();
    // this.getDealerUser();
    this.querySeries();
    this.queryModel();
  },
  methods: {
    createTopFilterList() {
      return [
        {
          type: 'RANGE_DATE',
          fieldName: 'inOutTimeStr|inOutTimeEnd',
          label: '结清日期',
          initialValue: [
            moment(new Date())
              .startOf('month')
              .format('YYYY-MM-DD'),
            moment(new Date()).format('YYYY-MM-DD')
          ],
          // labelOptions: {
          //   fieldName: 'inOutTime',
          //   initialValue: 'inTime',
          //   itemList: [
          //     { text: '送修日期', value: 'inTime' },
          //     { text: '审核日期', value: 'outTime' },
          //     { text: '结算日期', value: 'inOutTime' }
          //   ]
          // },
          rules: [{ required: true, message: '请选日期范围', trigger: 'change' }]
        },
        // {
        //   type: 'RANGE_DATE',
        //   label: '日期范围',
        //   fieldName: 'beginDate|endDate',
        //   placeholder: '选择日期',
        //   initialValue: [
        //     moment(new Date())
        //       .subtract(1, 'month')
        //       .format('YYYY-MM-DD'),
        //     moment(new Date()).format('YYYY-MM-DD')
        //   ],
        //   rules: [{ required: true, message: '请选日期范围', trigger: 'change' }]
        // },
        {
          type: 'SELECT',
          label: '类别',
          fieldName: 'repairTypeCode',
          placeholder: '请选择...',
          clearable: true,
          filterable: true,
          itemList: []
          // unitRender: () => {
          //   return <el-button slot="append" icon="el-icon-search" onClick={this.openManager6}></el-button>;
          // }
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'model',
          placeholder: '请选择...',
          clearable: true,
          filterable: true,
          itemList: []
          // unitRender: () => {
          //   return <el-button slot="append" icon="el-icon-search" onClick={this.openManager7}></el-button>;
          // }
        },
        {
          type: 'SELECT',
          label: '服务顾问',
          fieldName: 'serviceAdvisor',
          placeholder: '请选择...',
          clearable: true,
          filterable: true,
          itemList: []
          // unitRender: () => {
          //   return <el-button slot="append" icon="el-icon-search" onClick={this.openManager8}></el-button>;
          // }
        }
      ];
    },
    createTableCheckColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '服务顾问',
          dataIndex: 'SERVICE_ADVISOR',
          sorter: true,
          showOverflowTooltip: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          dictItems: []
        },
        {
          title: '维修类别',
          dataIndex: 'REPAIR_TYPE_NAME',
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          filterType: 'input'
        },
        {
          title: '车型',
          dataIndex: 'MODEL_NAME',
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          filterType: 'input'
        },
        {
          title: '厂牌',
          dataIndex: 'SERIES_NAME',
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          filterType: 'input'
        },
        {
          title: '车次',
          dataIndex: 'counts',
          sorter: true,
          filter: true,
          align: 'center',
          summation: true,
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '工时费',
          dataIndex: 'REAL_LABOUR_FEE',
          sorter: true,
          filter: true,
          align: 'right',
          precision: 2,
          summation: true,
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '材料费',
          dataIndex: 'REAL_REPAIR_PART_FEE',
          sorter: true,
          filter: true,
          align: 'right',
          precision: 2,
          summation: true,
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '包工费',
          dataIndex: 'BGF',
          sorter: true,
          filter: true,
          align: 'right',
          precision: 2,
          summation: true,
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '其他费用',
          dataIndex: 'OTHER_AMOUNT',
          sorter: true,
          filter: true,
          align: 'right',
          precision: 2,
          summation: true,
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '税额',
          dataIndex: 'TAX_AMOUNT',
          sorter: true,
          filter: true,
          align: 'right',
          precision: 2,
          summation: true,
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '合计金额',
          dataIndex: 'TOTAL_AMOUNT',
          sorter: true,
          filter: true,
          align: 'right',
          precision: 2,
          summation: true,
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '扣税合计',
          dataIndex: 'NOT_TOTAL_AMOUNT',
          sorter: true,
          filter: true,
          align: 'right',
          precision: 2,
          summation: true,
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '实际工时费',
          dataIndex: 'RECEIVEABLE_LABOUR_FEE',
          sorter: true,
          filter: true,
          align: 'right',
          precision: 2,
          summation: true,
          showOverflowTooltip: true,
          filterType: 'number'
        },
        {
          title: '实际材料费',
          dataIndex: 'RECEIVEABLE_REPAIR_PART_FEE',
          sorter: true,
          filter: true,
          align: 'right',
          precision: 2,
          summation: true,
          showOverflowTooltip: true,
          filterType: 'number'
        }
      ];
    },
    // 维修类型
    async querySeries() {
      const res = await getfindAllRepairType();
      let list = res.data.map(x => ({ text: x.REPAIR_TYPE_NAME, value: x.REPAIR_TYPE_CODE + '' }));
      this.topFilterList.find(item => item.fieldName === 'repairTypeCode').itemList = list; // 维修类型
    },
    // 获取所有人的信息
    /* async getDealerUser() {
      const res = await getDealerUser();
      let userData = arrayObjDeWeight(res.data, 'userId');
      this.serviceAdvisorDict = this.columns.find(x => x.dataIndex == 'SERVICE_ADVISOR').dictItems = this.columns.find(x => x.dataIndex == 'SERVICE_ADVISOR').filterItems = this.columns.find(
        x => x.dataIndex == 'SERVICE_ADVISOR'
      ).editItems = userData.map(x => ({
        text: x.employeeName,
        value: x.userId + ''
      }));
    },
    */
    // 车型
    async queryModel() {
      const res = await getModel();
      this.topFilterList.find(x => x.fieldName === 'model').itemList = res.data.map(x => ({ text: x.MODEL_NAME, value: x.MODEL_ID + '' }));
    },
    // 服务工程师  hyx
    async getFwgcsSelectFun() {
      let testDrive = { role: dictCode.SERVICE_CONSULTANT };
      const res = await searchRoleByCode(testDrive);
      this.topFilterList.find(item => item.fieldName === 'serviceAdvisor').itemList = res.data.map(x => ({ text: x.employeeName, value: x.userId }));

      this.columns.find(item => item.dataIndex === 'SERVICE_ADVISOR').filterItems = this.columns.find(item => item.dataIndex === 'SERVICE_ADVISOR').dictItems = res.data.map(x => ({
        text: x.employeeName,
        value: x.userId + ''
      }));
    },
    tableAllData(val) {},
    selectChangeHandle(val) {
      this.selectedRow = val;
    },
    async changeHandle(val) {
      this.dataSource = [];
      this.BaseTable.START_LOADING();
      // console.log('val', val);
      this.printList.inOutTimeStr = val.inOutTimeStr.slice(0, 10);
      this.printList.inOutTimeEnd = val.inOutTimeEnd.slice(0, 10);
      if (val.inOutTimeEnd) {
        val.inOutTimeStr = val.inOutTimeStr.slice(0, 10) + ' 00:00:00';
        val.inOutTimeEnd = val.inOutTimeEnd.slice(0, 10) + ' 23:59:59';
        val.inOutTime = 'inOutTime';
      }
      try {
        let res = await searchServiceAdvisor(val);
        if (res.resultCode == 200) {
          this.dataSource = res.data;
        }
      } catch (error) {
      } finally {
        this.BaseTable.STOP_LOADING();
      }
    },
    resetHandler() {
      this.printList = {};
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    async openHandle() {
      let data = await this.$refs.topFilter.GET_FORM_DATA();
      if (data[1].inOutTimeEnd) {
        data[1].inOutTimeStr = data[1].inOutTimeStr.slice(0, 10) + ' 00:00:00';
        data[1].inOutTimeEnd = data[1].inOutTimeEnd.slice(0, 10) + ' 23:59:59';
        data[1].inOutTime = 'inOutTime';
      }
      this.formData = data[1];
      console.log('formData', this.formData);
      this.isShowSummary = true;
    },
    saveHandle() {
      let printData = []; // 打印数组
      let serviceAdvisorList = []; // 存在的服务顾问
      let dataSource = _.cloneDeep(this.dataSource); // 打印数据
      // console.log('dataSource', dataSource);
      // console.log('serviceAdvisorDict', this.serviceAdvisorDict);
      for (const item1 of dataSource) {
        let key = this.serviceAdvisorDict.find(x => x.value == item1.SERVICE_ADVISOR);
        item1.SERVICE_ADVISOR = key ? key.text : item1.SERVICE_ADVISOR; // 维修顾问翻译
        if (serviceAdvisorList.indexOf(item1.SERVICE_ADVISOR) == -1) {
          serviceAdvisorList.push(item1.SERVICE_ADVISOR);
        }
        item1.RECEIVEABLE_LABOUR_FEE = item1.RECEIVEABLE_LABOUR_FEE.toFixed(2);
        item1.RECEIVEABLE_REPAIR_PART_FEE = item1.RECEIVEABLE_REPAIR_PART_FEE.toFixed(2);
        item1.BGF = item1.BGF.toFixed(2);
        item1.OTHER_AMOUNT = item1.OTHER_AMOUNT.toFixed(2);
        item1.TAX_AMOUNT = item1.TAX_AMOUNT.toFixed(2);
        item1.TOTAL_AMOUNT = item1.TOTAL_AMOUNT.toFixed(2);
        item1.NOT_TOTAL_AMOUNT = item1.NOT_TOTAL_AMOUNT.toFixed(2);
        item1.REAL_LABOUR_FEE = item1.REAL_LABOUR_FEE.toFixed(2);
        item1.REAL_REPAIR_PART_FEE = item1.REAL_REPAIR_PART_FEE.toFixed(2);
      }
      // console.log('serviceAdvisorList', serviceAdvisorList);
      for (const item2 of serviceAdvisorList) {
        let obj1 = {
          // 一级对象
          total: 0,
          data: []
        };
        let data1 = []; // 按维修顾问分组数据
        for (const item3 of dataSource) {
          if (item2 == item3.SERVICE_ADVISOR) {
            data1.push(item3);
          }
        }
        obj1.total = data1.length; // 该维修顾问拥有数据条数
        let repairType = []; // 每个维修顾问所涉及的维修类型
        for (const item4 of data1) {
          if (repairType.indexOf(item4.REPAIR_TYPE_NAME) == -1) {
            repairType.push(item4.REPAIR_TYPE_NAME);
          }
        }
        // console.log('repairType', repairType, data1);
        for (const item5 of repairType) {
          let obj2 = {
            // 二级对象
            total: 0,
            data: []
          };
          for (const item6 of data1) {
            if (item5 == item6.REPAIR_TYPE_NAME) {
              obj2.data.push(item6);
            }
          }
          obj2.total = obj2.data.length; // 该维修顾问的该种维修类型数据条数
          obj1.data.push(obj2); // 将二级对象放进一级对象里
        }
        printData.push(obj1); // 将一级对象放进打印数据里
      }
      this.printList.data = printData;
      console.log(this.printList, 'printList');
      this.$refs.print.EXCUTE_PRINT();
    }
  }
};
</script>
<style lang="less" scoped></style>
